var express = require('express');
var router = express.Router();
const Query = require('../tools/db')
const { image_url } = require('../config/config')
const timeStamp = require('time-stamp');
const formidable = require('formidable');
const fs = require('fs');
const path = require('path');
const { setToken, getToken } = require('../tools/token');
const { send } = require('process');

//验证token中间件(开发阶段先注册，完成后再放开)
// router.use((req, res, next) => {
//   // console.log(req.headers);//token
//   if (!getToken(req.headers.authorization)) {
//     //如果验证不成功，证明token传错了，或者过期了
//     next('身份验证失败，请登录');
//     return;
//   }
//   next();
// })

/* GET home page. */
//视频详情页
router.get('/videoplay/:id', async function (req, res, next) {
  let { id } = req.params;
  if (!id) {
    next('缺少必要的参数');
    return;
  }
  let sql = `SELECT *FROM e_video WHERE id = '${id}'`
  let [err, result] = await Query(sql);
  if (err) {
    next('服务器内部错误');
    return;
  }
  if (!result.length) {
    next('请传入正确的参数');
    return;
  }
  //对视频地址进行拼接
  result[0].video_src = `${image_url}/uploads/video/${result[0].video_src}`
  res.send({
    code: 200,
    msg: '获取成功',
    result: result[0]
  });
});
//获取课程报名数据
router.post('/study', async (req, res, next) => {
  //mid:用户mid   cid：课程的cid
  let { mid, cid } = req.body;
  if (!mid || !cid) {
    next('缺少必要的参数');
    return;
  }
  //1.查找是否已经报名这个课程
  let sql1 = `SELECT *FROM e_order WHERE cid='${cid}' AND mid = '${mid}'`
  let [err1, result1] = await Query(sql1);
  if (err1) {
    next('服务器内部错误');
    return;
  }
  if (result1.length) {
    next('已经报名过该课程');
    return;
  }
  // 2、报名课程
  // id : 自增
  // oid: 订单号 年月日时分秒+6位的随机数  算出来
  // cid: 课程id 打开某个详情页，一定是有课程id的 ？
  // mid: 用户id 用户标识（本地存储 token） ？
  // createdate: 订单的创建时间  算出来(时间戳)
  // status: 1
  let oid = timeStamp('YYYYMMDDHHmmss') + Math.random().toString().slice(2, 8);//订单号
  let createdate = Date.now();//创建时间(时间戳)；
  let sql2 = `INSERT INTO e_order (oid,cid,mid,createdate,status) VALUES ('${oid}','${cid}','${mid}','${createdate}','1')`
  let [err2, result2] = Query(sql2);
  if (err2) {
    next('服务器内部错误');
    return;
  }
  if (result2.affectedRows) {
    res.send({
      code: 200,
      msg: '报名成功',
    })
  } else {
    next('报名失败');
  }
})
//获取用户信息
router.get('/user', async (req, res, next) => {
  let { mid } = req.query;
  if (!mid) {
    next('请输入参数mid');
    return;
  }
  let sql = `SELECT *FROM e_member WHERE mid = '${mid}'`
  let [err, result] = await Query(sql);
  if (err) {
    next('服务器内部错误');
    return;
  }
  if (!result.length) {
    next('传入的mid有误');
    return;
  }
  delete result[0].password;//删除密码
  result[0].head_photo_url = image_url + '/uploads/photo/' + result[0].head_photo_url;
  res.send({
    code: 200,
    msg: '获取成功',
    result: result[0],
  })
})
//更改用户信息
router.put('/changeMsg', async (req, res, next) => {
  let { mid, realname = '', sex = 1, birthdate = '', city = '' } = req.body;
  if (!mid) {
    next('缺少必要的mid信息');
    return;
  }
  let sql = `UPLOAD e_member SET realname='${realname}',sex=${sex},birthdate='${birthdate}',city='${city}', WHERE mid='${mid}'`
  let [err, result] = await Query(sql);
  if (err) {
    next('服务器内部错误');
    return;
  }
  if (result.affectedRows) {
    res.send({
      code: 200,
      msg: '更新成功'
    })
  }
})
//更新用户头像
router.post('/uploadHead', (req, res, next) => {
  //实例化一个上传表单功能
  const form = formidable({
    uploadDir: path.join(__dirname, '../tempdir')//临时文件存放地,需要绝对地址
  })
  form.parse(req, async (err, fields, files) => {
    // err: 错误信息
    // fields : 普通的表单元素数据
    // files : 文件数据
    // 处理具体的业务。比如：文件名的重命名，把文件最终放在的位置是哪里
    if (err) {
      next('上传错误');
      return;
    }
    let { mid } = fields;//用户的mid
    if (!mid) {
      next('必须传入mid');
      return;
    }
    //将文件移入到永久储存中
    //新文件名
    let newFileName = timeStamp('YYYYMMDDmmss') + Math.random().toString().slice(2, 8) + path.extname(files.f.name);
    //path.extname(files.f.name)获取上传文件的后缀
    //改名移动文件
    fs.renameSync(files.f.path, path.join(__dirname, '../uploads/photo', newFileName));
    //更新数据库中的记录
    let sql = `UPLOAD e_member set head_photo_url ='${newFileName}' WHERE mid = '${mid}'`
    let [err1, result] = await Query(sql);
    if (err1) {
      next('服务器内部错误');
      return;
    }
    if (result.saffectedRows) {
      res.send({
        code: 200,
        msg: '更新成功',
        head_photo_url: image_url + '/uploads/photo' + newFileName
      })
    } else {
      next('请传入正确的mid')
    }
  })
})
//获取用户信息
router.get('/orders', async (req, res, next) => {
  let { mid } = req.body;
  if (!mid) {
    next('必须传入用户的mid');
    return;
  }
  let sql = `SELECT subiect_name,title,area_name,c.id,c.cid,CONCAT('${image_url}','/uploads/course/',image_src) as image_src FROM e_order as o JOIN e_course as c ON o.cid=c.cid WHERE mid ='${mid}'`
  let [err, result] = await Query(sql);
  if (err) {
    next('服务器内部错误');
    return;
  }
  res, send({
    code: 200,
    msg: '获取成功',
    result,
  })
})
module.exports = router;
